package com.neuedu.cockpit.controller;

import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.neuedu.cockpit.domain.HmCarInfo;
import com.neuedu.cockpit.service.IHmCarInfoService;
import com.neuedu.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.neuedu.common.annotation.Log;
import com.neuedu.common.core.controller.BaseController;
import com.neuedu.common.core.domain.AjaxResult;
import com.neuedu.common.enums.BusinessType;
import com.neuedu.common.utils.poi.ExcelUtil;
import com.neuedu.common.core.page.TableDataInfo;

/**
 * 车辆管理信息Controller
 * 
 * @author neuedu
 * @date 2024-04-22
 */
@RestController
@RequestMapping("/cockpit/info")
public class HmCarInfoController extends BaseController
{
    @Autowired
    private IHmCarInfoService hmCarInfoService;

    /**
     * 查询车辆管理信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(HmCarInfo hmCarInfo)
    {
        startPage();
        List<HmCarInfo> list = hmCarInfoService.selectHmCarInfoList(hmCarInfo);
        return getDataTable(list);
    }

    /**
     * 获取车辆管理信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(hmCarInfoService.selectHmCarInfoById(id));
    }

    /**
     * 通过登录用户的id以及车架号，获取车辆管理信息详细信息
     */
    @GetMapping(value = "/carInfos/{carVin}")
    public AjaxResult carInfos(String carVin)
    {
        Long userId = getUserId();
        //通过车架号跟userid查询车辆信息
        HmCarInfo hmCarInfo = hmCarInfoService.selectHmCarInfoByUserIdAndCarVin(userId, carVin);
        if(hmCarInfo != null){
            return AjaxResult.success(hmCarInfo);
        }else{
            return AjaxResult.error("当前用户未绑定任何车辆或绑定信息已变更");
        }
    }

    /**
     * 新增车辆管理信息
     */
    @Log(title = "车辆管理信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HmCarInfo hmCarInfo)
    {
        // 车架号校验
        boolean vinFlag = hmCarInfoService.checkVinOnlyOne(hmCarInfo.getCarVin());
        if(vinFlag) {
            return AjaxResult.error("车架号不能重复");
        }
        // nfc重复校验
        boolean nfcFlag = hmCarInfoService.checkNfcOnlyOne(hmCarInfo.getNfc());
        if(nfcFlag) {
            return AjaxResult.error("NFC编码不能重复");
        }
        return toAjax(hmCarInfoService.insertHmCarInfo(hmCarInfo));
    }

    /**
     * 通过车架号绑定车辆
     */
    @PostMapping(value = "/bindCarVin")
    public AjaxResult bindCarVin(@RequestBody HmCarInfo hmCarInfo)
    {
        // 是否换绑
        boolean changeVin = false;
        String vinNm = hmCarInfo.getCarVin();
        // 车架号不可空
        if(StringUtils.isEmpty(vinNm)) {
            return AjaxResult.error("车架号不能为空");
        }
        // 一个人绑定一台车
        Long userId = getUserId();
        HmCarInfo car = hmCarInfoService.selectInfoByUserId(userId);
        if(car != null) {
            // 用户重复绑定车架号
            if(car.getCarVin().equals(vinNm)) {
                return AjaxResult.error("不可重复绑定车架号");
            } else {
                // 换绑车架号
                changeVin = true;
                //return AjaxResult.error("车主不能绑定多辆汽车");
            }
        }
        HmCarInfo newCar = new HmCarInfo();
        newCar.setCarVin(vinNm);
        // 通过车架号查询
        boolean existFlag = hmCarInfoService.checkVinOnlyOne(vinNm);
        if(!existFlag) {
            return AjaxResult.error("该车架号不存在");
        }
        // 换绑情况。
        if(changeVin) {
            // 换绑的情况 需要清空之前的userid
            return toAjax(hmCarInfoService.resetCarVin(car.getId(), vinNm));
        } else {
            return toAjax(hmCarInfoService.bingCarVin(hmCarInfo));
        }
    }
    /**
     * 修改车辆管理信息
     */
    @Log(title = "车辆管理信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HmCarInfo hmCarInfo)
    {
        HmCarInfo hc = new HmCarInfo();
        hc.setCarVin(hmCarInfo.getCarVin());
        List<HmCarInfo> hl = hmCarInfoService.selectHmCarInfoListByVin(hc);
        if(!CollectionUtils.isEmpty(hl)) {
            if(hl.size() > 1) {
                return AjaxResult.error("车架号不可重复");
            }
            List<Long> idList = hl.stream().map(HmCarInfo::getId).collect(Collectors.toList());
            // 是否是老数据
            if(!idList.contains(hmCarInfo.getId())) {
                return AjaxResult.error("车架号已存在，不可重复");
            }
        }
        HmCarInfo hci = new HmCarInfo();
        hci.setNfc(hmCarInfo.getNfc());
        List<HmCarInfo> hlc = hmCarInfoService.selectHmCarInfoList(hci);
        if(!CollectionUtils.isEmpty(hlc)) {
            if(hlc.size() > 1) {
                return AjaxResult.error("NFC编号不可重复");
            }
            List<Long> idNfcList = hlc.stream().map(HmCarInfo::getId).collect(Collectors.toList());
            // 是否是老数据
            if(!idNfcList.contains(hmCarInfo.getId())) {
                return AjaxResult.error("NFC编号已存在，不可重复");
            }
        }

        return toAjax(hmCarInfoService.updateHmCarInfo(hmCarInfo));
    }

    /**
     * 删除车辆管理信息
     */
    @Log(title = "车辆管理信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {

        return toAjax(hmCarInfoService.deleteHmCarInfoByIds(ids));
    }

    /**
     * 解绑车辆跟用户关系
     */
    @GetMapping("/unlock/{id}")
    public AjaxResult unLock(@PathVariable Long id)
    {
        return toAjax(hmCarInfoService.unlockUserAndCar(id));
    }

    /**
     * 绑定车辆跟用户关系
     */
    @PostMapping("/lock")
    public AjaxResult Lock(@RequestBody HmCarInfo hmCarInfo)
    {
        return toAjax(hmCarInfoService.lockUserAndCar(hmCarInfo));
    }
}
